<template>
  <div class="cart-page">
    <header class="header">
      <div class="container">
        <div class="logo">
          <h1>拼多多</h1>
        </div>
        <nav class="nav">
          <router-link to="/">首页</router-link>
          <router-link to="/products">商品</router-link>
          <router-link to="/cart">购物车</router-link>
          <template v-if="userStore.isLoggedIn">
            <el-dropdown @command="handleCommand" trigger="click">
              <span class="user-info">
                <el-icon><User /></el-icon>
                {{ userStore.user.username }}
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="admin" v-if="userStore.user.username === 'admin'">管理后台</el-dropdown-item>
                  <el-dropdown-item command="logout" :divided="userStore.user.username === 'admin'">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
          <template v-else>
            <router-link to="/login" class="login-link">登录/注册</router-link>
          </template>
        </nav>
      </div>
    </header>

    <div class="container">
      <h2 class="page-title">我的购物车</h2>
      
      <div v-if="cartItems.length === 0" class="empty-cart">
        <el-empty description="购物车是空的">
          <el-button type="primary" @click="$router.push('/products')">去购物</el-button>
        </el-empty>
      </div>

      <div v-else>
        <el-table :data="cartItems" style="width: 100%">
          <el-table-column label="商品图片" width="120">
            <template #default="scope">
              <img :src="scope.row.image" :alt="scope.row.name" class="product-img">
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="price" label="单价" width="120">
            <template #default="scope">
              ¥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column label="数量" width="180">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.quantity" 
                :min="1" 
                :max="scope.row.stock"
                @change="updateQuantity(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="scope">
              <span class="total-price">¥{{ scope.row.total_price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button 
                type="danger" 
                size="small" 
                @click="removeItem(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="cart-summary">
          <div class="summary-item">
            <span class="label">商品总数：</span>
            <span class="value">{{ totalItems }} 件</span>
          </div>
          <div class="summary-item total">
            <span class="label">总计：</span>
            <span class="value">¥{{ totalPrice }}</span>
          </div>
          <div class="cart-actions">
            <el-button @click="clearCart">清空购物车</el-button>
            <el-button type="primary" size="large" @click="checkout">去结算</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, ArrowDown } from '@element-plus/icons-vue'
import { useUserStore } from '../stores'
import request from '../utils/request'

const router = useRouter()
const userStore = useUserStore()
const cartItems = ref([])

const handleCommand = (command) => {
  if (command === 'admin') {
    router.push('/admin/products')
  } else if (command === 'logout') {
    userStore.logout()
    ElMessage.success('已退出登录')
    router.push('/')
  }
}

// 计算总数量
const totalItems = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.quantity, 0)
})

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + parseFloat(item.total_price), 0).toFixed(2)
})

// 加载购物车
const loadCart = async () => {
  if (!userStore.user || !userStore.user.id) {
    ElMessage.warning('请先登录')
    // 跳转到登录页
    router.push({
      path: '/login',
      query: { redirect: '/cart' }
    })
    return
  }

  try {
    const res = await request.get(`/cart/${userStore.user.id}`)
    cartItems.value = res.data || []
  } catch (error) {
    ElMessage.error('加载购物车失败')
  }
}

// 更新数量
const updateQuantity = async (item) => {
  try {
    await request.put(`/cart/${item.id}`, { quantity: item.quantity })
    // 重新计算小计
    item.total_price = (item.price * item.quantity).toFixed(2)
    ElMessage.success('数量已更新')
  } catch (error) {
    ElMessage.error('更新失败')
    loadCart() // 重新加载
  }
}

// 删除商品
const removeItem = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await request.delete(`/cart/${id}`)
    ElMessage.success('删除成功')
    loadCart()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 清空购物车
const clearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await request.delete(`/cart/clear/${userStore.user.id}`)
    ElMessage.success('购物车已清空')
    loadCart()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清空失败')
    }
  }
}

// 去结算
const checkout = () => {
  ElMessage.info('结算功能待实现')
}

onMounted(() => {
  loadCart()
})
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 15px 0;
  margin-bottom: 40px;
}

.header .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo h1 {
  color: #E02E24;
  font-size: 24px;
}

.nav {
  display: flex;
  gap: 30px;
}

.nav a {
  text-decoration: none;
  color: #333;
  font-size: 16px;
  transition: color 0.3s;
}

.nav a:hover,
.nav a.router-link-active {
  color: #E02E24;
}

.page-title {
  font-size: 32px;
  margin-bottom: 30px;
}

.empty-cart {
  padding: 100px 0;
  text-align: center;
}

.product-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.total-price {
  color: #E02E24;
  font-weight: bold;
  font-size: 16px;
}

.cart-summary {
  margin-top: 30px;
  padding: 30px;
  background: #f5f5f5;
  border-radius: 8px;
  text-align: right;
}

.summary-item {
  font-size: 18px;
  margin-bottom: 15px;
}

.summary-item .label {
  color: #666;
  margin-right: 20px;
}

.summary-item.total {
  font-size: 24px;
  color: #E02E24;
  font-weight: bold;
  margin-bottom: 30px;
}

.summary-item.total .label {
  color: #333;
}

.cart-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #E02E24;
  font-weight: 500;
  cursor: pointer;
  padding: 8px 15px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: rgba(255, 103, 0, 0.1);
}

.login-link {
  color: #E02E24 !important;
  font-weight: 500;
}
</style>

